package com.at.service.impl;

import com.at.common.CustomException;
import com.at.entity.Setmeal;
import com.at.entity.SetmealDish;
import com.at.entity.SetmealDto;
import com.at.mapper.SetmealMapper;
import com.at.service.SetmealDishService;
import com.at.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    public void saveAndDish(SetmealDto setmealDto) {
        //1.保存菜品基本信息
        this.save(setmealDto);
        //2.获取菜品列表数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐和菜品关联信息 操作Setmeal_dish insert插入操作
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void removeAndDish(List<Long> ids) {

        //查询套餐状态 确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        //判断套餐下面菜品条数
        int count = this.count();
        if(count>0){
            throw new CustomException("套餐正在售卖中 不能删除");
        }
        //如果可以删除 先删除表中数据
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper1);
    }

}
